<template>
    <el-form  label-width="100px" status-icon >
        <el-row>
            <el-col :span="4" style="margin-right: 10px;">
                <el-form-item label="强制核销">
                    <el-switch v-model="auditForce" :active-value="'Y'"
                            :inactive-value="'N'"></el-switch>
                </el-form-item>
            </el-col>
            <el-col :span="18" >
                <el-form-item label="核销备注">
                    <el-input v-model="auditRemark"></el-input>
                </el-form-item>
            </el-col>
            
        </el-row>
    </el-form>
    <el-table
        ref="tableRef"
        :data="tableData"
        v-bind="tableDefaultAttribute"
        row-key="id"
        :max-height="tableHeight"
        table-layout="auto"
        @sort-change="handleSortChange"
    >
        <template #empty>
            <span>无数据</span>
        </template>
        <el-table-column type="selection" width="55" :align="'center'" />
        <template v-for="col in tableColumns" :key="col.prop">
            <el-table-column
                v-if="!col.isHidden"
                :align="col.align"
                :prop="col.prop"
                :label="col.label"
                :fixed="col.fixed"
                :formatter="col.formatter"
                :type="col.type"
                :width="col.width"
            >
                
            </el-table-column>
        </template>
    </el-table>
    <el-button-group class="bg">
        <el-button class="btn" type="primary" @click="audit"
            >核销</el-button>
        <el-button class="btn" type="primary" @click="onQuery"
            >查询</el-button>
    </el-button-group>
    
    
    <el-dialog
        v-model="dialogQueryVisible"
        title="发票核销应收付费用查询"
        draggable
        destroy-on-close
    >
        <QueryForm
            :queryItems="queryItems"
            @yh-closedialog="onCloseDialog"
        ></QueryForm>
    </el-dialog>
</template>
<script setup lang="ts" name="AuditInvoiceFeedet">
import { ref, reactive, onMounted } from 'vue';
import { storeToRefs } from 'pinia';
import { ElMessage, ElTable } from 'element-plus';
// import { Plus, Search } from '@element-plus/icons-vue';
import {
    isEmpty,
    forEach,
    
} from 'lodash';
import type { FeedetViewModel } from '@/common/types/business';
import {
    tableDefaultAttribute,
    useTableInfo,
    tableColumnDefault,
} from '@/hooks/useTable';
import type { FormFieldItem, QueryItem, TableColumn } from '@/common/types/app';
import { Request } from '@/app/request';
import {
    pickQueryFromTable,
    transFormatter,
    formatDate,
} from '@/common/tools';

import { useAppStore } from '@/store/app';
const props = defineProps<{
    invoiceids: number[]
}>();
const emit = defineEmits<{
    close: [];
}>();
const {
    currency,
    client,
    
    SelectOptionFeeInOut,
    SelectOptionYN,
    cyCfs,
    
    feecod,
    cntrOwner,
} = storeToRefs(useAppStore());
const tableRef = ref<InstanceType<typeof ElTable>>();
const tableData = ref<Array<FeedetViewModel>>([]);
const auditRemark = ref('');
const auditForce = ref('N');
const tableHeight = ref(100);


const onFormatter = (_row: any, column: any, cellValue: any) => {
    let data: { value: string | number; label: string }[];
    if (column['property'] === 'currency_cod') {
        data = currency.value;
    } else if (column['property'] === 'fee_unit_cod') {
        data = client.value;
    } else if (
        ['audit_finish_id', 'special_id', 'need_audit', 'audit_id'].includes(
            column['property'],
        )
    ) {
        data = SelectOptionYN.value;
    } else if (column['property'] === 'fee_in_out') {
        data = SelectOptionFeeInOut.value;
    } else if (column['property'] === 'cfs_cod') {
        data = cyCfs.value;
    } else if (column['property'] === 'fee_owner') {
        data = cntrOwner.value;
    } else if (column['property'] === 'fee_cod') {
        data = feecod.value;
    } else {
        return cellValue;
    }

    return transFormatter(cellValue, data);
};

const tableColumns = reactive<TableColumn[]>([
    {
        ...tableColumnDefault,
        order: 1,
        prop: 'fee_unit_cod',
        label: '客户',
        fixed: 'left',
        sortable: 'custom',
        formatter: onFormatter,
        formFieldItemType: 'single',
        optionalValues: client.value,
        width: 150,
    },
    {
        ...tableColumnDefault,
        order: 1,
        prop: 'cntr_owner',
        label: '成本中心',
        fixed: 'left',
        sortable: 'custom',
        formatter: onFormatter,
        formFieldItemType: 'single',
        optionalValues: cntrOwner.value,
        width: 150,
    },
    
    {
        ...tableColumnDefault,
        order: 4,
        prop: 'fee_cod',
        fixed: 'left',
        label: '费目',
        formatter: onFormatter,
        formFieldItemType: 'single',
        optionalValues: feecod.value,
        width: 80,
    },
    {
        ...tableColumnDefault,
        order: 2,
        prop: 'cntr',
        label: '箱号',
        sortable: 'custom',
        fixed: 'left',
        formFieldItemType: 'input',
        width: 150,
    },
    
    {
        ...tableColumnDefault,
        order: 5,
        prop: 'fee_in_out',
        label: '收付',
        formatter: onFormatter,
        formFieldItemType: 'single',
        optionalValues: SelectOptionFeeInOut.value,
        width: 80,
    },
    {
        ...tableColumnDefault,
        order: 6,
        prop: 'currency_cod',
        label: '币种',
        // formatter: onFormatter,
        formFieldItemType: 'input',
        // optionalValues: currency,
        width: 80,
    },
    {
        ...tableColumnDefault,
        order: 6,
        prop: 'fee_value',
        label: '单价',
        formFieldItemType: 'number',
        width: 80,
    },
    {
        ...tableColumnDefault,
        order: 6,
        prop: 'fee_ton',
        label: '数量',
        formFieldItemType: 'number',
        width: 80,
    },
    {
        ...tableColumnDefault,
        order: 6,
        prop: 'amount',
        label: '金额',
        formFieldItemType: 'number',
        width: 80,
    },
    {
        ...tableColumnDefault,
        order: 7,
        prop: 'fee_nam',
        label: '计费人员',
        formFieldItemType: 'input',
        width: 120,
    },
    {
        ...tableColumnDefault,
        order: 8,
        prop: 'fee_tim',
        label: '计费日期',
        formatter: formatDate,
        formFieldItemType: 'date',
        sortable: 'custom',
        width: 200,
    },
    {
        ...tableColumnDefault,
        order: 9,
        prop: 'audit_id',
        label: '核销标识',
        sortable: 'custom',
        formatter: onFormatter,
        formFieldItemType: 'single',
        optionalValues: SelectOptionYN.value,
        width: 200,
    },
    {
        ...tableColumnDefault,
        order: 9,
        prop: 'audit_finish_id',
        label: '核销完成标识',
        sortable: 'custom',
        formatter: onFormatter,
        formFieldItemType: 'single',
        optionalValues: SelectOptionYN.value,
        width: 200,
    },
    {
        ...tableColumnDefault,
        order: 10,
        prop: 'fee_bill_no',
        label: '账单号',
        sortable: 'custom',
        formFieldItemType: 'input',
        width: 200,
    },
    {
        ...tableColumnDefault,
        order: 10,
        prop: 'pay_no',
        label: '付款码',
        sortable: 'custom',
        formFieldItemType: 'input',
        width: 200,
    },
    {
        ...tableColumnDefault,
        order: 20,
        prop: 'remark',
        label: '备注',
        sortable: 'custom',
        width: 300,
    },
]);

const dialogQueryVisible = ref(false);
let queryWhere = {};

const onRefresh = async () => {
    const req = new Request('发票核销应收付查询', {
        skip: (currentPage.value - 1) * pageSize.value,
        take: pageSize.value,
        order: orders,
        ...queryWhere,
    });
    const r = await req.post();

    totalnum.value = r.ext;
    tableData.value.length = 0;

    if (!isEmpty(r.obj)) {
        tableData.value = r.obj;
    }
};
const {
    currentPage,
    orders,
    pageSize,
    totalnum,
    handleSizeChange,
    handleCurrentChange,
    handleSortChange,
} = useTableInfo(onRefresh);
onMounted(() => {
    // onRefresh();
    tableHeight.value =
        window.innerHeight -
        Math.ceil(tableRef.value?.$el.getBoundingClientRect().bottom) - 300;
    // alert(tableHeight.value);
});
const onCloseDialog = async (arg: any) => {
    if (dialogQueryVisible.value) {
        // 查询
        currentPage.value = 1;
        queryWhere = arg;
        onRefresh();

        dialogQueryVisible.value = false;
    }
};
const getSelectedIds = (): number[] => {
    const rows: Array<FeedetViewModel> = tableRef.value?.getSelectionRows() || [];
    if (rows.length === 0) {
        ElMessage.info({
            message: '请选择要核销数据',
        });
        return [];
    }
    const ids = Array<number>();
    forEach(rows, (v: FeedetViewModel) => {
        ids.push(v.id as number);
    });
    return ids;
}
const audit = async () => {
    const payids = getSelectedIds();
    if (payids.length === 0) {
        return;
    }
    const req = new Request('发票应收付核销', {
        force_audit: auditForce.value,
        audit_remark: auditRemark.value,
        invoiceIds: props.invoiceids,
        feedetids: payids
    });
    const r = await req.post();
    if (r.code > 100) {
        const msg = `核销发票金额${r.obj.invoice.sum}  核销应收付${r.obj.feedet.sum}`
        ElMessage.info({
            message: msg
        })
        emit('close');
    }
}
const onQuery = () => {
    dialogQueryVisible.value = true;
};
const queryItems: Array<QueryItem> = pickQueryFromTable(tableColumns);
</script>
<style lang="scss" scoped>
.bg {
    margin-top: 10px;

    .btn {
        margin-right: 10px;
    }
}

.page {
    float: right;
    margin-top: 10px;
}
</style>
